package org.xian.server;

import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xian.common.CommandManager;
import org.xian.common.Packet;
import org.xian.common.proto.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author : xian
 */
public class DispatchRequestHandler {

    static Logger logger = LoggerFactory.getLogger(DispatchRequestHandler.class);

    public static void handlerRequest(ChannelHandlerContext ctx, Packet packet) {
        int cmd = packet.getCmd();
        Class<?> aClass = CommandManager.getRequestClass(cmd);
        try {
            Method method = aClass.getMethod("parseFrom", byte[].class);
            // 请求内容反序列化
            Object object = method.invoke(aClass, packet.getPayload());
            // 根据 cmd 指令执行对应处理， 这里直接简单的 if else 搞定
            if (cmd == 100101) {
                LoginRequest_100101 login = (LoginRequest_100101) object;
                logger.info("Handler Login Request --> \n{}", login.toString());
                Other other = Other.newBuilder().setOtherMessage("welcome").setOtherToken("1234567890").build();
                LoginResponse_100101 response = LoginResponse_100101.newBuilder().setMessage("Login Success!").setToken("abcdefg").setOther(other).build();
                ctx.writeAndFlush(new Packet(100101, response.toByteArray()));
            }

            if (cmd == 100102) {
                SayHelloRequest_100102 hello = (SayHelloRequest_100102) object;
                logger.info("Handler SayHello Request --> \n{}", hello.toString());
                SayHelloResponse_100102 response = SayHelloResponse_100102.newBuilder().setHello("OK OK OK").build();
                ctx.writeAndFlush(new Packet(100102, response.toByteArray()));
            }


        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
